package com.example.mychat;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.mychat.Bean.User;

import org.litepal.LitePal;

import java.util.List;

public class loginActivity extends AppCompatActivity {
    private EditText userdit,psdedit;
    private Button loginbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        getUser();
        setListener();
    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn=userdit.getText().toString().trim();
                String psd=psdedit.getText().toString().trim();
                User user=confirmUser(usn,psd);
                if (user==null){
                    //登录失败
                }else {
                    Intent intent=new Intent(loginActivity.this,MainActivity.class);
                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("myid",user.getId());
                    editor.putString("myname",user.getName());
                    editor.putInt("myimg",user.getUserimg());
                    editor.apply();
                    startActivity(intent);
                    finish();
                }
            }
        });
    }
    private User confirmUser(String usn, String psd) {
        List<User> userList= LitePal.findAll(User.class);
        for(User u:userList){
            if (usn.equals(u.getName())&&psd.equals(u.getPassword())){
                return u;
            }
        }
        return null;
    }

    private void getUser() {
        new User(0,"张三","123").save();
        new User(1,"汤姆","456").save();
        new User(2,"王五","789").save();
    }

    private void initView() {
        userdit=findViewById(R.id.userdit);
        psdedit=findViewById(R.id.psdedit);
        loginbtn=findViewById(R.id.loginbtn);
    }
}
